package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.PurchaseService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseItemDoneVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Resource
    PurchaseDetailService purchaseDetailService;

    @Resource
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnReceivePurchase(Map<String, Object> params) {
        //只查询刚新建的采购单以及将要分配的采购单
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<PurchaseEntity>()
                .eq("status", 0).or().eq("status", 1);


        IPage<PurchaseEntity> page = this.page(new Query<PurchaseEntity>().getPage(params),wrapper);

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null) {
            //如果没有指定purchaseId,那么就需要新增一个采购单!
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setPriority(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            save(purchaseEntity);

            //返回的采购单id
            purchaseId = purchaseEntity.getId();
        }

        //TODO 需要确认采购单的状态是0或者1,才可以进行合并!

        List<Long> ids = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> detailEntities = ids.stream().map((id) -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(id);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());
        //更新这些采购细节的状态为已经分配!
        purchaseDetailService.updateBatchById(detailEntities);


        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(finalPurchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }


    @Override
    public void received(List<Long> ids) {
        //ids : 采购单id
        //1、确认当前采购单是新建或者已分配状态,已分配状态指的是被分配,但是还没人领取,
        //一但被领取就会变成已经领取,此时别人就不能领了,等于先到先得
        List<PurchaseEntity> purchaseEntities = ids.stream().map(id -> getById(id))
                .filter(item -> (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode())
                ||(item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()))
                .map(item -> {
                    item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    item.setUpdateTime(new Date());
                    return item;
                })
                .collect(Collectors.toList());

        //2、改变采购单的状态
        updateBatchById(purchaseEntities);

        //3、改变采购项的状态
        purchaseEntities.forEach(entity -> {
            //根据采购单的id找到该采购单上的所有采购项
            List<PurchaseDetailEntity> detailEntities =  purchaseDetailService.listDetailsByPurchaseId(entity.getId());

            List<PurchaseDetailEntity> updateEntities = detailEntities.stream().map((item) -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                //只更新这两项,所以new了个新对象(其实没必要,个人认为改变一下item的状态就行)
                detailEntity.setId(item.getId());
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());

            purchaseDetailService.updateBatchById(updateEntities);
        });



    }

    @Transactional
    @Override
    public void finish(PurchaseDoneVo purchaseDoneVo) {
        //1、改变采购项的状态
        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        List<PurchaseDetailEntity> willUpdates = new ArrayList<>();
        boolean flag = true;
        for (PurchaseItemDoneVo item : items) {
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag = false;
            }else {
                //3、将成功采购的进行入库
                PurchaseDetailEntity detailEntity = purchaseDetailService.getById(item.getItemId());

                wareSkuService.addStock(detailEntity.getSkuId()
                        ,detailEntity.getWareId()
                        ,detailEntity.getSkuNum());
            }
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item.getItemId());
            purchaseDetailEntity.setStatus(item.getStatus());
            willUpdates.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(willUpdates);

        //2、改变采购单状态 --> 必须所有的采购单全部都是已完成的状态,采购单状态才是已完成,
        //否则就是有异常!例如某个采购项缺货
        Long purchaseId = purchaseDoneVo.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        if (flag){
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
        }else {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        }
        updateById(purchaseEntity);
    }

}